<template>
  <rx-layout>
    <div slot="left" width="200" showButton="true">
      <rx-fit>
        <rx-category-treeeditor
          cat-key="BPM"
          :statisticConfig="statisticConfig"
          read-key="inst.read"
          :edit="false"
          @handSelect="selectTreeNode"
          :async="true"
          v-if="isShowManageTree"
          :isAdmin="isManageToTree"
          :treeRootList="treeRootList"
          :isBpmClient="isMyBpmClient"
          :isMyBpm="isMyBpmClient"
        ></rx-category-treeeditor>
      </rx-fit>
    </div>
    <div slot="center" style>
      <rx-fit :isheader="isheader">
        <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
            <rx-list-title :title="i18n('list.myStarted','我的发起')"></rx-list-title>
          <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
        </div>
        <div  btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel" @close="closeSearchbar">
          <a-form :layout="colLayout">
            <a-row :gutter="24">
              <a-col :span="colSpan">
                <a-form-item :label="i18n('form.billNo','业务单号')">
                  <a-input v-model="queryParam['Q_i.BILL_NO__S_EQ']" :placeholder="i18n('form.billNo','请输入业务单号','input')" />
                </a-form-item>
              </a-col>
              <a-col :span="colSpan">
                  <a-form-item :label="i18n('form.title','标题')">
                      <a-input :placeholder="i18n('form.title','请输入标题','input')" v-model="queryParam.Q_SUBJECT__S_LK" />
                  </a-form-item>
              </a-col>
              <a-col :span="colSpan">
            <a-form-item :label="i18n('form.status','运行状态')">
              <a-select v-model="queryParam['Q_i.STATUS__S_EQ']">
                <a-select-option value="DRAFTED">{{i18n('statusMap.draft','草稿')}}</a-select-option>
                <a-select-option value="RUNNING">{{i18n('statusMap.run','运行')}}</a-select-option>
                <a-select-option value="SUPSPEND">{{i18n('statusMap.suspend','暂停')}}</a-select-option>
                <a-select-option value="SUCCESS_END">{{i18n('statusMap.end','结束')}}</a-select-option>
              </a-select>
            </a-form-item>
              </a-col>
              <a-col :span="colSpan" v-if="isheader">
                    <span class="table-page-search-submitButtons">
                      <a-button type="primary"  icon="search" @click="search">{{$ti18('rxList.searchBtn','查询')}}</a-button>
                      <a-button style="margin-left: 4px"  @click="cancel">{{$ti18('rxList.resetBtn','重置')}}</a-button>
                      <a @click="toggleAdvanced" style="margin-left: 8px">
                        {{ advanced ? i18n('list.putAwayBtn','收起') : i18n('list.expansionBtn','展开') }}
                        <a-icon :type="advanced ? 'up' : 'down'" />
                      </a>
                    </span>
              </a-col>
              <template v-if="advanced">
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('list.createTime','创建时间') + i18n('list.from','从')">
                  <a-date-picker
                    :placeholder="i18n('list.createTime','请输入创建时间','input')"
                    v-model="queryParam['Q_i.CREATE_TIME__D_GE']"
                    @change="searchRangeDateChange($event,$event,{queryField:'Q_i.CREATE_TIME__D_GE'},'YYYY-MM-DD')"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                  </a-col>
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('list.to','至')">
                  <a-date-picker
                    :placeholder="i18n('list.createTime','请输入创建时间','input')"
                    v-model="queryParam['Q_i.CREATE_TIME__D_LE']"
                    @change="searchRangeDateChange($event,$event,{queryField:'Q_i.CREATE_TIME__D_LE'},'YYYY-MM-DD')"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                  </a-col>

              </template>
            </a-row>
          </a-form>
        </div>
        <rx-grid
          ref="table"
          v-if="isShowManageTree"
          bordered
          :allowRowSelect="true"
          :allowMoveColumn="true"
          :multiSelect="true"
          :columns="columns"
          :defaultPageSize="10"
          url="/api-bpm/bpm/core/bpmInst/myBpmInsts"
          :queryParam="queryParam"
          data-field="result.data"
          :pageSizeOptions="['10', '30', '40']"
          id-field="instId"
          :loadDataOnstart="true"
          @selectChange="onSelectChange"
          :srcoll="{ x: 1000 }"
          @getListData="loadDataAgen"
        >
          <span slot="status" slot-scope="{ text, status }">
            <a-tag :color="statusMap[text]?statusMap[text].color:''">
              <span>{{ statusMap[text].text }}</span>
            </a-tag>
          </span>
          <span slot="isLive" slot-scope="{ text,status }">
            <a-tag :color="isLiveMap[text].color">
              <span>{{isLiveMap[text].text}}</span>
            </a-tag>
          </span>
            <span slot="appId" slot-scope="{ text, record }">
                {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
            </span>
            <span slot="billNo" slot-scope="{ text, record, index }">
                {{ record.billNo }}
            </span>
          <span slot="action" slot-scope="{ text, record }" class="actionIcons">
            <rx-span @click="onDetail(record)" :btnConfig="btnConfig" :lable="$ti18('rxList.detailBtn','明细')" alias="detailBtn">{{$ti18('rxList.detailBtn','明细')}}</rx-span>
            <template v-if="record.status == 'DRAFTED'">
              <rx-span @click="startFlow(record)" :btnConfig="btnConfig" :lable="i18n('form.start','启动')" alias="startBtn">{{i18n('form.start','启动')}}</rx-span>
            </template>
            <template v-else>
              <rx-span v-if="record.status == 'SUPSPEND'" @click="restoreInst(record)" :btnConfig="btnConfig" :lable="i18n('statusMap.restore','恢复')" alias="restoreBtn">{{i18n('statusMap.restore','恢复')}}</rx-span>
              <rx-span v-if="record.status == 'RUNNING'" @click="supspendInst(record)" :btnConfig="btnConfig" :lable="i18n('statusMap.suspend','暂停')" alias="suspendBtn">{{i18n('statusMap.suspend','暂停')}}</rx-span>
              <rx-span v-if="record.status!='CANCEL'&&record.status!='ARCHIVED'" @click="cancelInst(record)" :btnConfig="btnConfig" :lable="i18n('statusMap.cancel','作废')" alias="cancelBtn">{{i18n('statusMap.cancel','作废')}}</rx-span>
            </template>
            <rx-span v-if="findAuthRight('inst.delete') && removeEnable" @click="delByIds([record.instId])" :btnConfig="btnConfig" :lable="$ti18('rxList.delBtn','删除')" alias="myDelBtn"
              >{{$ti18('rxList.delBtn','删除')}}</rx-span
            >
          </span>
        </rx-grid>
      </rx-fit>
      <a-modal :title="i18n('list.voidTitle','流程作废提示')" v-model="cancelVisiable" @ok="onCancelInst">
        <p>{{i18n('msa.voidTips','您确定需要作废该流程吗？')}}</p>
        <p>{{i18n('msa.voidCause','作废原因：')}}</p>
        <p>
          <a-textarea v-model="cancelReason"></a-textarea>
        </p>
      </a-modal>
    </div>
  </rx-layout>
</template>

<script>
import BpmInstApi from '@/api/bpm/core/bpmInst'
import BpmInstLiveSelect from "../core/BpmInstLiveSelect";
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import { BaseList, RxLayout, Util, RxGrid, RxFit,RxSpan } from '@lowcode/jpaas-common-lib'
import FlowUtil from "../js/FlowUtil";
import { mapState} from 'vuex';
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import instAndTaskShare from "@/views/modules/bpm/core/js/instAndTaskShare";
export default {
  name: 'MyBpmInstList',
  mixins: [BaseList,instAndTaskShare,FlowUtil,AppSearch],
  components: {
    RxLayout,
    RxGrid,
    RxFit,
    RxSpan,
    RxCategoryTreeeditor,
    RxSearchApp
  },
    computed: {
        ...mapState({
            // 所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
        btnConfig(){
            return {
                showNoRight: false,
                user:this.user,
                buttons:this.buttons,
                allButtons:this.allButtons
            }

        }
    },
  data() {
    return {
      treeData: [],
      statusMap: {
        DRAFTED: { color: 'gray', text: this.i18n('statusMap.draft','草稿') },
        LOCKED: { color: 'black', text: this.i18n('statusMap.lock','锁定') },
        INVOKE_TO_STARTOR: { color: 'red', text: this.i18n('statusMap.withdrawToStartor','撤回(发起人)') },
        RUNNING: { color: 'red', text: this.i18n('statusMap.running','运行中') }, //运行
        SUPSPEND: { color: 'black', text: this.i18n('statusMap.suspend','暂停') }, //运行
        CANCEL: { color: 'red', text: this.i18n('statusMap.cancel','作废') }, //作废
        SUCCESS_END: { color: 'green', text: this.i18n('statusMap.success','成功') }, // 成功结束
        ERROR_END: { color: 'red', text: this.i18n('statusMap.abort','异常结束') }, //异常结束
      },
      isLiveMap:{
        YES:{ color:'red', text:this.i18n('form.revived','已复活')},
        NO:{ color:'green' ,text:this.i18n('form.unrevived','未复活')}
      },
      cancelVisiable: false,
      cancelInstId: '',
      cancelReason: '', //流程作废原因
      //显示搜索

      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: this.$ti18('rxList.index','序号'),
          type: 'indexColumn',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 60,
        },
        {
          title: this.i18n('form.title','标题'),
          dataIndex: 'subject',
          width: 200,
        },
        {
          title: this.i18n('form.billNo','业务单号'),
            scopedSlots: { customRender: 'billNo' },
          dataIndex: 'billNo',
          width: 150,
        },
        {
          title: this.i18n('form.status','运行状态'),
          dataIndex: 'status',
          width: 110,
          scopedSlots: { customRender: 'status' },
        },
      {
          title: this.i18n('form.appId','所属应用'),
          dataIndex: 'appId',
          width: 140,
          sortField: 'APP_ID_',
          scopedSlots: {customRender: 'appId'}
      },
        {
          title: this.$ti18('rxForm.createTime','创建时间'),
          dataIndex: 'createTime',
          width: 160,
        },
        {
          title: this.$ti18('rxList.action','操作'),
          dataIndex: 'action',
            fixed:'right',
          scopedSlots: { customRender: 'action' },
          width: 120,
        },
      ],
      curTree: {},
      statisticConfig: {
          type:"static_bpm",
          appIdPrefix:'t.',
          table:"BPM_INST t left join BPM_DEF d on t.DEF_ID_ = d.DEF_ID_",
          field:"t.TREE_ID_",
          whereConf:[{name:"CREATE_BY_",alias:"t.CREATE_BY_",type:"string",dateFormat:"",op:"=",value:"curUserId",valueType:"context"}]
      },
        isMyBpmClient:true,
        readKey:"task.read",
        readType:"instStartHist",
        isInit:true,
        treePrefix:'i.',
    }
  },
  created(){
      this.addAppId();
      debugger
  },
  methods: {
      i18n(name,text,key){
          return this.$ti18(name,text,"MyBpmInst",key);
      },
      addAppId(){
          let appId=this.curApp.appId;
          if(appId){
              this.queryParam["Q_i.APP_ID__S_EQ"]=appId;
          }
      },
    selectTreeNode(curRow) {
        this.loadDataBySelectTreeNode(curRow);
    },
    onDetail(record) {
      this.openDetail(record.appId,record.instId,"mystart");
    },
    startFlow(record) {
        this.openInst(record.appId,record.instId);
    },
    restoreInst(record) {
      BpmInstApi.updateProcessStatus(record.instId, 'RUNNING').then((resp) => {
        this.refreshGrid()
      })
    },
    supspendInst(record) {
      BpmInstApi.updateProcessStatus(record.instId, 'SUPSPEND').then((resp) => {
        this.refreshGrid()
      })
    },
    cancelInst(record) {
      this.cancelVisiable = true
      this.cancelInstId = record.instId
    },
    onCancelInst() {
      let self_ = this
      BpmInstApi.cancelProcess(this.cancelInstId, this.cancelReason).then((resp) => {
        self_.cancelReason = ''
        self_.cancelInstId = ''
        self_.cancelVisiable = false
        self_.refreshGrid()
      })
    },
    handleOk() {
      this.$refs.table.loadData()
    },
    delByIds(ids) {
      let self_ = this
      this.$confirm({
        title: this.$ti18('rxMsa.actionTips','操作提示'),
        content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
          okText: this.$ti18('rxForm.ackBtn','确认'),
          cancelText: this.$ti18('rxForm.cancelBtn','取消'),
        onOk() {
          BpmInstApi.delBpmInst({ ids: ids.join(',') }).then((res) => {
            if (res.success && res.code == 200) {
              self_.handleOk()
            }
            self_.selectedRowKeys = []
          })
        },
        onCancel() {},
      })
    },
    onLiveProcess(){
      var row=this.$refs.table.getSelectedRow();
      if(!row || (row.status!="SUCCESS_END" && row.status!="ERROR_END")) {
        this.$message.error(this.i18n('msa.reviveUnfinished','无法复活未结束的流程！'));
        return;
      }
      if(row.isLive=="YES"){
        this.$message.error(this.i18n('msa.reviveResurrected','无法复活已复活的流程！'));
        return;
      }
      var self_=this;
      Util.open({
        component: BpmInstLiveSelect,
        curVm:this,
        widthHeight:['1024px','600px'],
        title: this.i18n('list.revivePageTitle','复活流程实例') +"【"+row.subject+"】",
        data:{
          instId:row.instId
        }
      },function (action,data){
        if(action!='ok')return;
        BpmInstApi.liveProcess({
          actInstId:row.actInstId,
          destNodeUsers:data.destNodeUsers,
          opinion:data.opinion,
          opFiles:data.opFiles
        }).then(res=>{
          self_.refreshGrid();
        })
      });
    },
    searchRangeDateChange(date,dateString,e,format){
        if(date.length==2){
            this.queryParam[e.queryField]=date[0].format('YYYY-MM-DD');
        }else {
            this.queryParam[e.queryField]=date.format(format);
        }
    },
    search() {
      this.$refs.table.loadData()
    },
    closeSearchbar(){
      //关闭过滤弹窗；（点击X触发）
      this.fitSearch = false ;
    },
  },
}
</script>
